import os
import re
import sys
from pathlib import Path

def fix_file_syntax(file_path):
    """修复文件中的语法错误"""
    print(f"Processing file: {file_path}")
    
    # 尝试多种编码读取文件
    encodings = ['utf-8', 'gbk', 'gb2312', 'latin1', 'cp1252']
    content = None
    encoding_used = None
    
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
            encoding_used = encoding
            print(f"  Successfully read with encoding: {encoding}")
            break
        except UnicodeDecodeError:
            continue
    
    if content is None:
        print(f"  Could not read file with any encoding")
        return False
    
    # 分割为行
    lines = content.split('\n')
    fixed_lines = []
    brace_stack = []
    paren_stack = []
    
    for i, line in enumerate(lines):
        line_num = i + 1
        fixed_line = line
        
        # 检查括号匹配
        open_parens = line.count('(') - line.count(')')
        if open_parens > 0:
            paren_stack.extend(['('] * open_parens)
        elif open_parens < 0:
            # 添加缺失的左括号
            for _ in range(abs(open_parens)):
                if paren_stack:
                    paren_stack.pop()
        
        # 检查引号匹配
        quote_count = line.count('"')
        if quote_count % 2 == 1:
            print(f"    Line {line_num}: Unmatched quotes found, fixing...")
            # 添加引号来结束字符串
            if line.strip().endswith('"'):
                # 行以引号结尾，可能需要在开头添加引号
                fixed_line = '"' + line
            else:
                # 在行尾添加引号
                fixed_line = line + '"'
        
        # 处理包含非UTF-8字符的行
        try:
            fixed_line.encode('utf-8')
        except UnicodeEncodeError:
            # 如果不能编码为UTF-8，移除非UTF-8字符
            try:
                clean_line = ''.join(c for c in fixed_line if ord(c) < 128 or c in '\n\r\t')
                fixed_line = clean_line
                print(f"    Line {line_num}: Cleaned non-UTF-8 characters")
            except:
                print(f"    Line {line_num}: Skipping problematic line")
                # 添加一个注释行
                fixed_line = f"// Line {line_num}: Original line contained invalid characters"
        
        fixed_lines.append(fixed_line)
    
    # 检查是否需要在文件末尾添加括号
    if paren_stack:
        print(f"  Adding missing closing parentheses at end of file")
        for _ in paren_stack:
            fixed_lines.append(')')
    
    # 写回文件
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(fixed_lines))
        print(f"  Successfully fixed file")
        return True
    except Exception as e:
        print(f"  Error writing file: {e}")
        return False

def find_problematic_files():
    """查找可能有问题的Java文件"""
    # 基于之前的错误信息，我们可以确定哪些文件需要修复
    problematic_files = [
        "gate-server/src/main/java/com/lastwar/gateserver/login/LoginHandler.java",
        "gate-server/src/main/java/com/lastwar/gateserver/session/SessionManager.java"
    ]
    
    return problematic_files

def main():
    # 从命令行参数获取文件路径，如果没有提供则使用默认路径
    if len(sys.argv) > 1:
        file_path = sys.argv[1]
        files_to_fix = [file_path]
    else:
        files_to_fix = find_problematic_files()
    
    for file_path in files_to_fix:
        if not os.path.isabs(file_path):
            # 如果是相对路径，基于当前脚本目录
            script_dir = os.path.dirname(os.path.abspath(__file__))
            file_path = os.path.join(script_dir, file_path)
        
        if os.path.isfile(file_path):
            fix_file_syntax(file_path)
        else:
            print(f"File not found: {file_path}")

if __name__ == "__main__":
    main()